package com.bolt.support.json.fastjson;

import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.bolt.common.utils.StrUtil;

import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * Created by Administrator on 2020/2/28.
 */
public class LocalDateDeserializer  implements ObjectDeserializer {

    public static final LocalDateDeserializer instance = new LocalDateDeserializer();

    private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
        // 如果是字符串格式
        String value = parser.getLexer().stringVal();
        parser.getLexer().nextToken();
        if(StrUtil.isEmpty(value)){
            return null;
        }
        if (value.contains("-")) {
            if (type.equals(LocalDateTime.class)) {
                return (T) LocalDateTime.parse(value, dateTimeFormatter);
            } else {
                return (T) LocalDate.parse(value, dateTimeFormatter);
            }
        }

        long longValue = Long.parseLong(value) / 1000;
        if (type.equals(LocalDateTime.class)) {
            return (T) LocalDateTime.ofEpochSecond(longValue, 0, ZoneOffset.ofHours(8));
        } else if (type.equals(LocalDate.class)) {
            return (T) LocalDateTime.ofEpochSecond(longValue, 0, ZoneOffset.ofHours(8)).toLocalDate();
        }

        return null;
    }

    @Override
    public int getFastMatchToken() {
        return 0;
    }
}



 